import React from 'react'
import { useMemo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { toggleTodo, delTodo, setModalTitle, setModalContent, setIsShowModal } from '../store/todoList';

function ItemList() {
  console.log('itemList组件渲染了')
  const { todoList, filter } = useSelector(state => state.todoList)
  const dispatch = useDispatch()
  // 查
  const viewTodo = (id) => {
    dispatch(setModalTitle('查看事件'))
    dispatch(setModalContent({ isViewContent: true, id }))
    dispatch(setIsShowModal(true))
  }
  // 改
  const editTodo = (id) => {
    dispatch(setModalTitle('编辑事件'))
    dispatch(setModalContent({ isViewContent: false, id }))
    dispatch(setIsShowModal(true))
  }
  // 筛选
  const filterTodos = useMemo(() => {
    console.log('useMemo filterTodos 触发了')
    if (filter === 'done') {
      return todoList.filter(obj => obj.completed)
    } else if (filter === 'todo') {
      return todoList.filter(obj => !obj.completed)
    } else {
      return todoList
    }
  }, [todoList, filter])
  return (
    <div className="itemList">
      {filterTodos.map(obj => {
        return <div className="item" key={obj.id} >
          <input 
            id={`itemCheckbox` + obj.id} 
            type="checkbox" 
            className="checkbox" 
            checked={obj.completed}
            onChange={() => dispatch(toggleTodo(obj.id))}
          />
          <label
            className="label"
            htmlFor={`itemCheckbox` + obj.id}
            style={{textDecoration: obj.completed ? 'line-through' : 'none'}}
          >
            {obj.title}
          </label>
          <button className="btn view" onClick={() => viewTodo(obj.id)}>查看</button>
          <button className="btn edit" onClick={() => editTodo(obj.id)}>编辑</button>
          <button className="btn del" onClick={() => dispatch(delTodo(obj.id))}>删除</button>
        </div>
      })}
    </div>
  )
}

export default React.memo(ItemList)